<template>
  <el-cascader
    v-model="selectKeys"
    :options="categories"
    placeholder="试试搜索, 手机"
    filterable
    clearable
    :props="props"
    ref="cascader"
    @change="handleChange"></el-cascader>
</template>

<script>
export default {
  // 接收父组件传来的值
  props: {
    catelogPath: {
      type: Array,
      default(){
        return [];
      }
    }
  },
  watch: {
    catelogPath (path) {
      console.log("---&&", path)
      this.selectKeys = this.catelogPath;
    }
  },
  data () {
    return {
      selectKeys: this.catelogPath,
      categories: [],
      props: {
        expandTrigger: 'hover',
        value: 'catId',
        label: 'name',
        children: 'childList'
      }
    }
  },
  methods: {

    handleChange(data){
      console.log("改变选择-抽取的组件", this.selectKeys)

      let temp = this.categories
      let checkNode
      for (let i = 0; i < this.selectKeys.length; i++) {
        for (let j = 0; j < temp.length; j++) {
          if(this.selectKeys[i] === temp[j].catId){
            checkNode = temp[j]
            temp = temp[j].childList
            break
          }
        }
      }
      this.$emit("change-value", data, checkNode)
      this.PubSub.publish("catPath",data);
    },

    getCategories () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get',
        param: this.$http.adornParams()
      }).then((response) => {
        // this.categories = JSON.parse(response.data.data)
        for (let i = 0; i < response.data.data.length; i++) {
          //深拷贝
          this.categories.push(response.data.data[i])
        }
      }).catch(() => {
        console.log("=========error==========")
        this.$message({
          type: 'error',
          message: '网络异常'
        });
      })
    }
  },
  created() {
    this.getCategories()
  }
}
</script>
